package doantotnghiep.daoimpl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;

import doantotnghiep.dao.CustomerDao;
import doantotnghiep.model.Customer;

public class CustomerDaoImpl implements CustomerDao {

	@Autowired
	private HibernateTemplate hibernateTemplate;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Customer> listCustomer() {
		return hibernateTemplate.find("from Customer where status = 0 order by id");
	}
	
	@Override
	public void deleteCustomer(int id) {
		Customer entity = this.findCustomerByID(id);
		if (entity != null){
			entity.setStatus(1);
			this.hibernateTemplate.saveOrUpdate(entity);
		}	
	}

	@Override
	public void saveCustomer(Customer customer) {
		this.hibernateTemplate.saveOrUpdate(customer);		
	}

	@Override
	public void addCustomer(Customer customer) {
		this.hibernateTemplate.saveOrUpdate(customer);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Customer findCustomerByID(int id) {
		List<Customer> customers = hibernateTemplate.find("from Customer where status = 0 and id ="+ id);
		if(customers!=null){
			return customers.get(0);
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Customer> getListcustomerByKey(String key) {		
		List<Customer> list= hibernateTemplate.find("from Customer where status = 0 and fullName like '%"+key+"%'");
		return list;
	}

}
